package com.common.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.common.StarAppConfig;
import com.common.StarAppConst;
import com.common.activity.StarAppLocalAlbumMultiSelect;
import com.common.allCommon.StarAppHeadImageLoader;
import com.common.bean.NetStateChangeReceiver;
import com.common.commonInterface.INetStateChangeCallback;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.product.android.business.ApplicationVariable;
import com.product.android.utils.SharedPreferenceHelper;
import com.starappallcommon.R;

/**
 * 明星app工具类
 * 
 * <br>
 * Created 2014-5-5 下午2:37:37
 * 
 * @version
 * @author zhy
 * 
 * @see
 */
public final class StarAppUtils {

	/** 实例 */
	private static StarAppUtils instance = new StarAppUtils();

	/** 私有构造函数 */
	private StarAppUtils() {
	}

	/**
	 * 获取实例
	 * 
	 * @函数名称 :getInstance
	 * @brief
	 * @see
	 * @since Ver 1.1
	 * @return StatappUtils实例
	 * @作者 : HuangYK
	 * @创建时间 : 2014-5-5下午12:40:33
	 */
	public static StarAppUtils getInstance() {
		if (instance == null) {
			instance = new StarAppUtils();
		}
		return instance;
	}

	/**
	 * 语音的长度毫秒改成秒, 如果有余数加1
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:37:50
	 * 
	 * @param time
	 *            时间
	 * @return int
	 * @author : zhy
	 */
	public static int millsec2Sec(long time) {
		final double conver = 1000.0;
		return Double.valueOf(Math.ceil(time / conver)).intValue();
	}

	/**
	 * 获得SD卡中应用程序数据目录
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:38:08
	 * 
	 * @param ctx
	 *            上下文
	 * @return 目录字符串
	 * @author : HuangYK
	 */
	public static String getSDCardCacheDir(Context ctx) {
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
			if (ctx.getExternalCacheDir() == null) {
				return "";
			}
			return makesureFileSepInTheEnd(ctx.getExternalCacheDir().getPath());
		} else {
			if (!isSdCardExist()) {
				return "";
			}
			return String.format(Locale.getDefault(),
					Environment.getExternalStorageDirectory()
							+ "/Android/data/%s/cache/", ctx.getPackageName());
		}
	}

	/**
	 * 确保末尾的斜杠
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:38:30
	 * 
	 * @param strDir
	 *            路径字符串
	 * @return String
	 * @author : HuangYK
	 */
	public static String makesureFileSepInTheEnd(String strDir) {
		if (!TextUtils.isEmpty(strDir)) {
			// 确保以斜杠结尾
			if (!strDir.endsWith(File.separator)) {
				strDir += File.separator;
			}
		}

		return strDir;
	}

	/**
	 * 判断SD卡是否存在
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:38:45
	 * 
	 * @return boolean
	 * @author : HuangYK
	 */
	public static boolean isSdCardExist() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;

	}

	/**
	 * 从sdcard中移除所有尺寸的头像缓存
	 * 
	 * <br>
	 * Created 2014-5-5 下午2:39:02
	 * 
	 * @param uid
	 *            用户uid
	 * @author : suchangjun
	 */
	public static void removeFaceCache(long uid) {
		ImageLoader.getInstance().removeFromDiscCache(
				StarAppHeadImageLoader.mFaceCircleDisplayOptions,
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_40));

		ImageLoader.getInstance().removeFromMemCache(
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_40));

		ImageLoader.getInstance().removeFromDiscCache(
				StarAppHeadImageLoader.mFaceCircleDisplayOptions,
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_100));

		ImageLoader.getInstance().removeFromMemCache(
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_100));

		ImageLoader.getInstance().removeFromDiscCache(
				StarAppHeadImageLoader.mFaceCircleDisplayOptions,
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_152));

		ImageLoader.getInstance().removeFromMemCache(
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_152));

		ImageLoader.getInstance().removeFromDiscCache(
				StarAppHeadImageLoader.mFaceCircleDisplayOptions,
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_640));

		ImageLoader.getInstance().removeFromMemCache(
				StarAppHeadImageLoader.getFaceUrl(uid,
						StarAppHeadImageLoader.FACE_SIZE_640));

	}

	/**
	 * 清除二维码图片缓存
	 * 
	 * <br>
	 * Created 2014-5-9 下午4:23:45
	 * 
	 * @param qrCodeUrl
	 *            二维码Url
	 * @author : HuangYK
	 */
	public static void removdQRCodeCache(String qrCodeUrl) {
		ImageLoader.getInstance().removeFromMemCache(qrCodeUrl);
		ImageLoader.getInstance().removeFromDiscCache(null, qrCodeUrl);
	}

	/**
	 * 打开系统照相机
	 * 
	 * <br>
	 * Created 2014-5-7 下午5:34:36
	 * 
	 * @param activity
	 *            界面上下文对象
	 * @param photoFile
	 *            存储拍照后文件的对象,需要初始化好传入，否则无用
	 * @param quality
	 *            拍照质量
	 * @param requestCode
	 *            请求码
	 * @author : HuangYK
	 */
	public static void openSystemCamera(Activity activity, File photoFile,
			final int quality, final int requestCode) {
		if (null == photoFile) {
			return;
		}
		Intent intent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		Uri localUri = Uri.fromFile(photoFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, quality);
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 调用系统相机，屏蔽第三方相机
	 * 
	 * <br>
	 * Created 2014-9-23 上午11:17:45
	 * 
	 * @param activity
	 *            界面上下文对象
	 * @param photoFile
	 *            存储拍照后文件的对象,需要初始化好传入，否则无用
	 * @param quality
	 *            拍照质量
	 * @param requestCode
	 *            请求码
	 * @author : HuangYK
	 */
	public static void openSystemCameraWithOutOther(Activity activity,
			File photoFile, final int quality, final int requestCode) {
		final Intent intent = new Intent();

		final String sysCameraPackage = "com.android.camera";
		final String meizuCameraPackage = "com.android.camera.meizu";
		final String meizu2CameraPackage = "com.meizu.camera";
		final String meizu3CameraPackage = "com.android.gallery3d";
		final String samsungCameraPackage = "com.sec.android.app.camera";
		final String huaweiCameraPackage = "com.android.hwcamerahelp";
		final String htcCameraPackage = "com.htc.camera";
		// LG的相机
		final String lgCameraPackage = "com.google.android.GoogleCamera";
		// LG的相机
		final String lgeCameraPackage = "com.lge.camera";
		// =======star 索尼=======//
		final String sonyCameraPackage = "com.sonymobile.android.camera";
		final String sony2CameraPackage = "com.sonymobile.camera";
		final String sony3CameraPackage = "com.sonyericsson.android.addoncamera";
		final String sony4CameraPackage = "com.sonymobile.cameracommon";
		final String sony5CameraPackage = "com.sonyericsson.cameracommon";
		final String sony6CameraPackage = "com.sonyericsson.android.camera";
		final String sony7CameraPackage = "com.sonyericsson.android.camera3d";
		// =======end 索尼=======//

		// 如果可以获取到系统相机，则设置为系统相机打开
		if (activity.getPackageManager().getLaunchIntentForPackage(
				meizuCameraPackage) != null) {
			// 魅族
			intent.setPackage(meizuCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				meizu2CameraPackage) != null) {
			// 魅族
			intent.setPackage(meizu2CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				meizu3CameraPackage) != null) {
			// 魅族
			intent.setPackage(meizu3CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sysCameraPackage) != null) {
			// 原生系统
			intent.setPackage(sysCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				samsungCameraPackage) != null) {
			// 三星系统
			intent.setPackage(samsungCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				htcCameraPackage) != null) {
			// HTC系统
			intent.setPackage(htcCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				lgCameraPackage) != null) {
			// LG系统
			intent.setPackage(lgCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				lgeCameraPackage) != null) {
			// LG系统
			intent.setPackage(lgeCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				huaweiCameraPackage) != null) {
			// 华为系统
			intent.setPackage(huaweiCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sonyCameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sonyCameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony2CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony2CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony3CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony3CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony3CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony3CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony4CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony4CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony5CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony5CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony6CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony6CameraPackage);
		} else if (activity.getPackageManager().getLaunchIntentForPackage(
				sony7CameraPackage) != null) {
			// 索尼系统
			intent.setPackage(sony7CameraPackage);
		}

		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		Uri localUri = Uri.fromFile(photoFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, quality);

		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 打开浏览本地相册界面
	 * 
	 * <br>
	 * Created 2014-5-7 下午5:36:08
	 * 
	 * @param activity
	 *            界面上下文对象
	 * @param isMultiSelect
	 *            是否是多选，true：多选，false：单选
	 * @param requestCode
	 *            请求码
	 * @param paths
	 *            已经选取的图片路径，用于多选 说明：返回的是
	 *            StarAppLocalAlbumMultiSelect.SELECTED_IMG
	 *            是一个已经选择图片路径ArrayList<String>。
	 * @author : HuangYK
	 */
	public static void openLocalAlbum(Activity activity, boolean isMultiSelect,
			ArrayList<String> paths, int requestCode) {
		Intent intent = new Intent(activity, StarAppLocalAlbumMultiSelect.class);
		intent.putStringArrayListExtra(
				StarAppLocalAlbumMultiSelect.IMAGE_PATHS, paths);
		intent.putExtra(StarAppLocalAlbumMultiSelect.IS_MULTI_SELECT,
				isMultiSelect);
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 打开浏览本地相册界面
	 * 
	 * <br>
	 * Created 2014-9-29 下午3:10:45
	 * 
	 * @param activity
	 *            界面上下文对象
	 * @param isMultiSelect
	 *            是否是多选，true：多选，false：单选
	 * @param isUsedGif
	 *            是否使用GIF
	 * @param paths
	 *            已经选取的图片路径，用于多选 说明：返回的是
	 *            StarAppLocalAlbumMultiSelect.SELECTED_IMG
	 *            是一个已经选择图片路径ArrayList<String>。
	 * @param requestCode
	 *            请求码
	 * @author : HuangYK
	 */
	public static void openLocalAlbum(Activity activity, boolean isMultiSelect,
			boolean isUsedGif, ArrayList<String> paths, int requestCode) {
		Intent intent = new Intent(activity, StarAppLocalAlbumMultiSelect.class);
		intent.putStringArrayListExtra(
				StarAppLocalAlbumMultiSelect.IMAGE_PATHS, paths);
		intent.putExtra(StarAppLocalAlbumMultiSelect.IS_MULTI_SELECT,
				isMultiSelect);
		intent.putExtra(StarAppLocalAlbumMultiSelect.IS_USED_GIF, isUsedGif);
		activity.startActivityForResult(intent, requestCode);
	}

	/**
	 * 获取dimines在xml配置中的原值
	 * 
	 * <br>
	 * Created 2014-5-13 下午3:09:09
	 * 
	 * @param context
	 *            上下文
	 * @param unit
	 *            属性单位
	 * @param value
	 *            属性值
	 * @return dimines在xml配置中的原值 参考
	 *         {@link TypedValue#applyDimension(int, float, DisplayMetrics)}
	 * @author : HuangYK
	 */
	public static float getDiminesOriginalValue(Context context, int unit,
			float value) {
		DisplayMetrics metrics = new DisplayMetrics();
		metrics = context.getResources().getDisplayMetrics();

		switch (unit) {
		case TypedValue.COMPLEX_UNIT_PX:
			return value;
		case TypedValue.COMPLEX_UNIT_DIP:
			return value / metrics.density;
		case TypedValue.COMPLEX_UNIT_SP:
			return value / metrics.scaledDensity;
		case TypedValue.COMPLEX_UNIT_PT:
			final int value2 = 72;
			return value / (metrics.xdpi * (1.0f * value2));
		case TypedValue.COMPLEX_UNIT_IN:
			return value / metrics.xdpi;
		case TypedValue.COMPLEX_UNIT_MM:
			final float value3 = 25.4f;
			return value / (metrics.xdpi * (1.0f / value3));
		default:
			return 0;
		}
	}

	/**
	 * 获取dimines中字体大小原值
	 * 
	 * <br>
	 * Created 2014-5-13 下午3:15:19
	 * 
	 * @param context
	 *            上下文
	 * @param diminesId
	 *            dimines的资源id
	 * @return dimines中字体大小原值
	 * @author : HuangYK
	 */
	public static float getDiminesSpValue(Context context, int diminesId) {
		float value = context.getResources().getDimension(diminesId);
		return getDiminesOriginalValue(context, TypedValue.COMPLEX_UNIT_SP,
				value);
	}

	/**
	 * 判断是否点击视图控件外
	 * 
	 * <br>
	 * Created 2014-5-15 下午2:46:23
	 * 
	 * @param v
	 *            View 视图控件
	 * @param event
	 *            MotionEvent 触屏事件
	 * @return 是否点击视图控件外
	 * @author chenqian
	 */
	public static boolean isTouchViewOutside(View v, MotionEvent event) {
		if (v != null) {
			int[] leftTop = { 0, 0 };
			v.getLocationInWindow(leftTop);
			int left = leftTop[0], top = leftTop[1], bottom = top
					+ v.getHeight(), right = left + v.getWidth();
			float x = event.getX();
			float y = event.getY();
			return !(x > left && x < right && y > top && y < bottom);
		}
		return false;
	}

	/**
	 * 判断sdcard是否存在
	 * 
	 * <br>
	 * Created 2014-6-24 下午4:52:58
	 * 
	 * @return sdcard是否存在
	 * @author chenqian
	 */
	public static boolean isSDCardExist() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	/**
	 * 将id列表转成JSONArray
	 * 
	 * <br>
	 * Created 2014-6-27 上午11:55:44
	 * 
	 * @param pids
	 *            图片id列表
	 * @return JSONArray
	 * @author : huangszh
	 */
	public static JSONArray convertToJSONArray(ArrayList<Long> pids) {
		if (pids == null) {
			return null;
		}

		int length = pids.size();
		JSONArray array = new JSONArray();
		for (int i = 0; i < length; i++) {
			array.put(pids.get(i));
		}
		return array;
	}

	/**
	 * 判断文件后缀名是否有效
	 * 
	 * <br>
	 * Created 2014-7-10 上午10:49:19
	 * 
	 * @param strExtension
	 *            后缀名
	 * @return true：有效，false：无效
	 * @author : HuangYK
	 */
	public static boolean judgeExtensionIsValid(String strExtension) {
		final String strJPG = "JPG";
		final String strJPGE = "JPGE";
		final String strPNG = "PNG";
		final String strBMP = "BMP";
		if (TextUtils.isEmpty(strExtension)) {
			return false;
		}
		strExtension = strExtension.toUpperCase();

		if (strExtension.equals(strJPG) || strExtension.equals(strJPGE)
				|| strExtension.equals(strPNG) || strExtension.equals(strBMP)) {
			return true;
		}

		return false;
	}

	/**
	 * 判断文件后缀名是否有效
	 * 
	 * <br>
	 * Created 2014-9-29 下午3:06:36
	 * 
	 * @param strExtension
	 *            后缀名
	 * @param isUsedGif
	 *            是否使用GIF
	 * @return true：有效，false：无效
	 * @author : HuangYK
	 */
	public static boolean judgeExtensionIsValid(String strExtension,
			boolean isUsedGif) {
		final String strGIF = "GIF";
		boolean result = false;

		if (TextUtils.isEmpty(strExtension)) {
			return false;
		}
		strExtension = strExtension.toUpperCase();

		if (isUsedGif && strExtension.equals(strGIF)) {
			return true;
		}
		result = false;

		return judgeExtensionIsValid(strExtension) || result;
	}

	/**
	 * 根据文件名获取文件扩展类型
	 * 
	 * <br>
	 * Created 2014-7-10 上午10:55:54
	 * 
	 * @param filename
	 *            文件名
	 * @return 文件扩展类型
	 * @author : HuangYK
	 */
	public static String getExtFromFilename(String filename) {
		int dotPosition = filename.lastIndexOf('.');
		if (dotPosition != -1) {
			return filename.substring(dotPosition + 1, filename.length());
		}
		return "";
	}

	/**
	 * 注册网络状态变化的广播接收
	 * 
	 * <br>
	 * Created 2014-7-15 下午4:24:27
	 * 
	 * @param ctx
	 *            Context
	 * @param receiver
	 *            NetStateChangeReceiver
	 * @param callback
	 *            INetStateChangeCallback
	 * @author chenqian
	 */
	public static void registerNetStateChangeReceiver(Context ctx,
			NetStateChangeReceiver receiver, INetStateChangeCallback callback) {
		if (null != ctx) {
			if (null == receiver) {
				receiver = new NetStateChangeReceiver(callback);
			}
			ctx.registerReceiver(receiver, new IntentFilter(
					ConnectivityManager.CONNECTIVITY_ACTION));
		}
	}

	/**
	 * 解注册网络状态变化的广播接收
	 * 
	 * <br>
	 * Created 2014-7-15 下午4:28:59
	 * 
	 * @param ctx
	 *            Context
	 * @param receiver
	 *            NetStateChangeReceiver
	 * @author chenqian
	 */
	public static void unregisterNetStateChangeReceiver(Context ctx,
			NetStateChangeReceiver receiver) {
		if (ctx != null && receiver != null) {
			ctx.unregisterReceiver(receiver);
		}
	}

	/**
	 * 转到activity
	 * 
	 * <br>
	 * Created 2014-7-30 下午2:18:28
	 * 
	 * @param ctx
	 *            Context
	 * @param cls
	 *            Class<?>
	 * @author chenqian
	 */
	public static void goToActivity(Context ctx, Class<?> cls) {
		if (null == ctx || null == cls) {
			return;
		}
		Intent intent = new Intent(ctx, cls);
		ctx.startActivity(intent);
	}

	/**
	 * 设置视图的字体
	 * 
	 * <br>
	 * Created 2014-7-30 下午6:59:56
	 * 
	 * @param view
	 *            视图对象
	 * @param isBold
	 *            是否粗体
	 * @author : HuangYK
	 */
	public static void setViewTypeFace(TextView view, boolean isBold) {
        // 如果不需要使用特殊字体，直接返回
        if (!StarAppConfig.getBooleanConfig(StarAppConfig.IS_USED_SPECIAL_FONT)) {
            return;
        }
        if (view == null) {
			return;
		}
		view.setTypeface(StarAppConst.getInstance().getLTXTypeface());
		if (isBold) {
			view.getPaint().setFakeBoldText(true);
		}
	}

	public static void hideBottomSmartbar(Activity activity, View contentView) {
		int height = ApplicationVariable.INSTANCE.displayMetrics.heightPixels;
		Display display = activity.getWindowManager().getDefaultDisplay();
		DisplayMetrics dm = new DisplayMetrics();

		try {
			Class<?> c;
			c = Class.forName("android.view.Display");
			Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
			method.invoke(display, dm);
			if (height == dm.heightPixels) {
				Class<?>[] arrayOfClass = new Class[1];
				arrayOfClass[0] = Integer.TYPE;
				Method localMethod = View.class.getMethod(
						"setSystemUiVisibility", arrayOfClass);
				Field localField = View.class
						.getField("SYSTEM_UI_FLAG_HIDE_NAVIGATION");
				Object[] arrayOfObject = new Object[1];
				arrayOfObject[0] = localField.get(null);
				localMethod.invoke(contentView, arrayOfObject);
			}
		} catch (Exception e) {
			Log.e("HYK", "去除底部虚拟按键栏出错");
		}
	}

	/**
	 * 将图片修改为一个白色边框的圆角正六边形图片
	 * 
	 * <br>
	 * Created 2014-9-4 上午11:57:14
	 * 
	 * @param frameSize
	 *            边框宽度
	 * @param color
	 *            颜色资源id
	 * @param res
	 *            资源
	 * @param size
	 *            大小
	 * @param image
	 *            原图
	 * @return 处理好的图片
	 * @author : HuangYK
	 */
	public static Bitmap createHexagonPhoto(int frameSize, int color,
			Resources res, int size, Bitmap image) {

		// 正六边形，斜边等于高度的一半
		float mSideLength = size / 2;

		final int semicircle = 180;

		// 根据源文件新建一个darwable对象
		Drawable imageDrawable = new BitmapDrawable(res, image);

		// 新建一个新的输出图片，注意，这里一定要用ARGB_8888
		Bitmap contentBitmap = Bitmap.createBitmap(size, size,
				Bitmap.Config.ARGB_8888);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setColor(Color.WHITE);
		// 路径，用来描绘形状
		Path path = new Path();

		Canvas canvas = new Canvas(contentBitmap);
		// 新建一个矩形
		RectF outerRect = new RectF(0, 0, size, size);

		// 30度
		final float degrees30 = 30;
		// 角度，用来计算角坐标
		final float radian30 = (float) (degrees30 * Math.PI / semicircle);
		// 直角短边
		float a30 = (float) (mSideLength * Math.sin(radian30));
		// 直角长边
		float b30 = (float) (mSideLength * Math.cos(radian30));

		float leftX = mSideLength - b30;
		// 顶部坐标
		float[] coor1 = new float[] { mSideLength, 0 };
		// 左上角坐标
		float[] coor2 = new float[] { leftX, a30 };
		// 左下角坐标
		float[] coor3 = new float[] { leftX, size - a30 };
		// 底部坐标
		float[] coor4 = new float[] { mSideLength, size };
		// 右下角坐标
		float[] coor5 = new float[] { mSideLength + b30, size - a30 };
		// 右上角坐标
		float[] coor6 = new float[] { mSideLength + b30, a30 };

		// ========开始描绘六边形图片========
		// 定位到顶部
		path.moveTo(coor1[0], coor1[1] + frameSize);
		// 描绘左上方的边
		path.lineTo(coor2[0] + frameSize, coor2[1] + frameSize);
		// 描绘左侧的边
		path.lineTo(coor3[0] + frameSize, coor3[1] - frameSize);
		// 描绘左下方的边
		path.lineTo(coor4[0], coor4[1] - frameSize);
		// 描绘右下方的边
		path.lineTo(coor5[0] - frameSize, coor5[1] - frameSize);
		// 描绘右侧的边
		path.lineTo(coor6[0] - frameSize, coor6[1] + frameSize);
		// 根据起始位置，封闭六边形
		path.close();
		// 根据path画出六边形
		canvas.drawPath(path, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		imageDrawable.setBounds(0, 0, size, size);
		canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
		imageDrawable.draw(canvas);
		canvas.restore();

		canvas = null;
		paint.reset();
		path.reset();
		image.recycle();
		imageDrawable = null;
		// ========完成描绘六边形图片========

		// ========开始描绘六边形边框的========
		imageDrawable = new BitmapDrawable(res, contentBitmap);
		Bitmap frameBitmap = Bitmap.createBitmap(size, size,
				Bitmap.Config.ARGB_8888);
		Canvas frameCanvas = new Canvas(frameBitmap);
		RectF frameRect = new RectF(0, 0, size, size);
		paint.setFlags(Paint.ANTI_ALIAS_FLAG);
		paint.setColor(color);

		// 定位到顶部
		path.moveTo(coor1[0], coor1[1]);
		// 描绘左上方的边
		path.lineTo(coor2[0], coor2[1]);
		// 描绘左侧的边
		path.lineTo(coor3[0], coor3[1]);
		// 描绘左下方的边
		path.lineTo(coor4[0], coor4[1]);
		// 描绘右下方的边
		path.lineTo(coor5[0], coor5[1]);
		// 描绘右侧的边
		path.lineTo(coor6[0], coor6[1]);
		// 根据起始位置，封闭六边形
		path.close();
		// 根据path画出六边形
		frameCanvas.drawPath(path, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
		imageDrawable.setBounds(0, 0, size, size);
		frameCanvas.saveLayer(frameRect, paint, Canvas.ALL_SAVE_FLAG);
		imageDrawable.draw(frameCanvas);
		frameCanvas.restore();

		frameCanvas = null;
		paint.reset();
		path.reset();
		contentBitmap.recycle();
		imageDrawable = null;
		// ========完成描绘六边形边框的边框========

		final float bound = size / 20;
		// 圆角高度
		final float radian = bound / 2;

		// ========开始画圆角========
		imageDrawable = new BitmapDrawable(res, frameBitmap);
		Bitmap roundBitmap = Bitmap.createBitmap(size, size,
				Bitmap.Config.ARGB_8888);
		Canvas roundCanvas = new Canvas(roundBitmap);
		RectF roundRect = new RectF(0, 0, size, size);
		paint.setFlags(Paint.ANTI_ALIAS_FLAG);
		paint.setStyle(Paint.Style.STROKE);
		paint.setColor(color);
		paint.setStrokeWidth(radian);

		RectF roundContentRect = new RectF();
		roundContentRect.left = radian;
		roundContentRect.top = radian;
		roundContentRect.right = size - radian;
		roundContentRect.bottom = size - radian;
		path.arcTo(roundContentRect, 0, 180);
		path.arcTo(roundContentRect, 180, 180);
		path.close();
		roundCanvas.drawPath(path, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
		imageDrawable.setBounds(0, 0, size, size);
		roundCanvas.saveLayer(roundRect, paint, Canvas.ALL_SAVE_FLAG);
		imageDrawable.draw(roundCanvas);
		roundCanvas.restore();

		roundCanvas = null;
		paint.reset();
		path.reset();
		frameBitmap.recycle();
		imageDrawable = null;
		// ========完成画圆角========

		// ========开始最后的圆角处理========
		imageDrawable = new BitmapDrawable(res, roundBitmap);
		Bitmap roundFrameBitmap = Bitmap.createBitmap(size, size,
				Bitmap.Config.ARGB_8888);
		Canvas roundFrameCanvas = new Canvas(roundFrameBitmap);
		RectF roundFrameRect = new RectF(0, 0, size, size);
		paint.setFlags(Paint.ANTI_ALIAS_FLAG);
		paint.setColor(color);

		RectF rFrameRect = new RectF();
		rFrameRect.left = radian;
		rFrameRect.top = radian;
		rFrameRect.right = size - radian;
		rFrameRect.bottom = size - radian;
		path.arcTo(rFrameRect, 0, 180);
		path.arcTo(rFrameRect, 180, 180);
		path.close();
		roundFrameCanvas.drawPath(path, paint);

		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		imageDrawable.setBounds(0, 0, size, size);
		roundFrameCanvas.saveLayer(roundFrameRect, paint, Canvas.ALL_SAVE_FLAG);
		imageDrawable.draw(roundFrameCanvas);
		roundFrameCanvas.restore();

		roundFrameCanvas = null;
		paint.reset();
		path.reset();
		roundBitmap.recycle();
		imageDrawable = null;
		// ========完成最后的圆角处理========

		return roundFrameBitmap;
	}

	/**
	 * 
	 * <br>
	 * Created 2014-9-2 下午2:35:14
	 * 
	 * @param strPhone
	 *            手机号原格式
	 * @return 按XXX XXXX XXXX 方式分隔手机号
	 * @author gpy
	 */
	public static String phoneFormatIn(String strPhone) {
		if (TextUtils.isEmpty(strPhone)) {
			return "";
		}
		/** 手机控制空格位置1:3 */
		int PHONE_FORMAT1 = 3;
		/** 手机控制空格位置2:8 */
		int PHONE_FORMAT2 = 8;
		phoneFormatOut(strPhone);
		int length = strPhone.length();
		if (length > PHONE_FORMAT1) {
			strPhone = strPhone.substring(0, PHONE_FORMAT1) + " "
					+ strPhone.substring(PHONE_FORMAT1, length);
			if (length >= PHONE_FORMAT2) {
				strPhone = strPhone.substring(0, PHONE_FORMAT2) + " "
						+ strPhone.substring(PHONE_FORMAT2, strPhone.length());
			}
		}
		return strPhone;
	}

	/**
	 * 
	 * <br>
	 * Created 2014-9-2 下午2:35:14
	 * 
	 * @param strPhoneFormat
	 *            格式化手机号
	 * @return 原手机号
	 * @author gpy
	 */
	public static String phoneFormatOut(String strPhoneFormat) {
		if (TextUtils.isEmpty(strPhoneFormat)) {
			return "";
		}
		strPhoneFormat = strPhoneFormat.replaceAll(" ", "");
		return strPhoneFormat;
	}

	/**
	 * 格式化时间。<br>
	 * 发布时间 <1小时：显示分钟，例如35分钟前。<br>
	 * 24小时>发布时间>=1小时：显示小时，例如23小时前。<br>
	 * 48小时>发布时间>=24小时 显示 昨天 XX:XX （24小时制）。<br>
	 * 发布时间>=48小时,显示具体的日期 3月22日。<br>
	 * 发布时间>=365天 显示显示年份,例如2013年12月2日。<br>
	 * 在需求开发过程中发现JAY和个人空间中时间显示规则不一致， 经过和策划沟通，确认整个APP时间显示规则一致，并且以个人空间描述规则为准。<br>
	 * 
	 * @n<b>函数名称</b> :getSpecialShowTime
	 * @brief
	 * @see
	 * @since Ver 1.2
	 * @param timestamp
	 *            待转换的时间 单位s。<br>
	 * @return 转换后的时间
	 * @<b>作者</b> : suchangjun
	 * @<b>创建时间</b> : 2014-3-20上午10:18:40
	 */
	public static String getSpecialShowTime(long timestamp) {
		Context ctx = ApplicationVariable.INSTANCE.applicationContext;
		final long milli = 1000L;
		final int oneDay = 24;
		final int twoDay = oneDay * 2;

		Calendar now = Calendar.getInstance();
		long ms = 1000 * (now.get(Calendar.HOUR_OF_DAY) * 3600
				+ now.get(Calendar.MINUTE) * 60 + now.get(Calendar.SECOND));// 毫秒数
		long ms_now = now.getTimeInMillis();

		// String ret = "";
		// if(ms_now - timestamp < ms){
		// ret = datesdf1.format(createTime);
		// }else if(ms_now-create<(ms+24*3600*1000)){
		// ret = datesdf2.format(createTime);
		// }else if(ms_now-create<(ms+24*3600*1000*2)){
		// ret = datesdf3.format(createTime);
		// }else{
		// ret= datesdf4.format(createTime);
		// }

		timestamp *= milli;
		long diffSecond = System.currentTimeMillis() - timestamp;
		if (diffSecond < 0) {
			diffSecond = 0;
		}

		final long MINUTE = 60 * milli;
		final long HOUR = MINUTE * 60;

		// 发布时间小时1小时显示分钟。
		if (diffSecond < HOUR) {
			long minute = diffSecond / MINUTE;
			if (minute == 0) {
				minute = 1;
			}
			return minute
					+ ctx.getResources().getString(R.string.minutes_before);
			// } else if (diffSecond < (oneDay * HOUR)) {
		} else if (ms_now - timestamp < ms) {
			// 24小时>发布时间>=1小时：显示小时，例如23小时前
			long data = diffSecond / HOUR;
			if (data == 0) {
				data = 1;
			}
			return data + ctx.getResources().getString(R.string.hour_before);

			// } else if (diffSecond < (twoDay * HOUR)) {
		} else if (ms_now - timestamp < (ms + 24 * 3600 * 1000)) {
			// 48小时>发布时间>=24小时，显示 昨天 14:50
			String yesterday = ctx.getResources().getString(R.string.yesterday);
			Calendar base = Calendar.getInstance();
			base.setTimeInMillis(timestamp);
			int minute = base.get(Calendar.MINUTE);
			String minuteStr = minute + "";
			// 如果小于10那么就在前面显示加零
			final int tenths = 10;
			if (minute < tenths) {
				minuteStr = "0" + minute;
			}
			return yesterday + " " + base.get(Calendar.HOUR_OF_DAY) + ":"
					+ minuteStr;

		} else {
			// 这里面处理的就是显示>=48小时的
			Calendar base = Calendar.getInstance();
			base.setTimeInMillis(timestamp);
			int diffYear = now.get(Calendar.YEAR) - base.get(Calendar.YEAR);

			if (diffYear == 0) {
				// 那么说明是同一年的，只要显示日期和月份
				return (base.get(Calendar.MONTH) + 1)
						+ ctx.getResources().getString(R.string.month)
						+ base.get(Calendar.DAY_OF_MONTH)
						+ ctx.getResources().getString(R.string.day);
			} else {
				// 超过一年要显示年份
				return base.get(Calendar.YEAR)
						+ ctx.getResources().getString(R.string.year)
						+ (base.get(Calendar.MONTH) + 1)
						+ ctx.getResources().getString(R.string.month)
						+ base.get(Calendar.DAY_OF_MONTH)
						+ ctx.getResources().getString(R.string.day);
			}

		}

	}

	/**
	 * 毫秒为单位的时间戳转为字符串
	 * 
	 * <br>
	 * Created 2014-9-16 上午11:17:08
	 * 
	 * @param timestamp
	 *            时间戳
	 * @return 转换后的时间
	 * @see {@link #getSpecialShowTime(long)}
	 * @author : HuangYK
	 */
	public static String getSpecialShowTimeMS(long timestamp) {
		final int offset = 1000;
		return getSpecialShowTime(timestamp / offset);
	}

	/**
	 * 微秒为单位的时间戳转为字符串
	 * 
	 * <br>
	 * Created 2014-9-16 上午11:17:08
	 * 
	 * @param timestamp
	 *            时间戳
	 * @return 转换后的时间
	 * @see {@link #getSpecialShowTime(long)}
	 * @author : HuangYK
	 */
	public static String getSpecialShowTimeMicroS(long timestamp) {
		final int offset = 1000000;
		return getSpecialShowTime(timestamp / offset);
	}

	/**
	 * 获取群头像保存路径
	 * 
	 * <br>
	 * Created 2014-11-17 下午6:35:11
	 * 
	 * @param context
	 *            上下文
	 * @param groupId
	 *            群ID
	 * @return 群头像保存路径
	 * @author : HuangYK
	 */
	public static String getGroupAvatorSavePath(Context context, long groupId) {
		final String GROUP_AVATOR_NAME = "head/group_avator_";
		String cacheDir = StarAppUtils.getSDCardCacheDir(context);

		if (TextUtils.isEmpty(cacheDir)) {
			return null;
		}
		String filename = GROUP_AVATOR_NAME + groupId + ".jpg";

		return new File(cacheDir, filename).getPath();
	}

	
	/**
     * 根据本地时间获取默认群名
     * 
     * <br>Created 2014-12-5 下午5:26:54
     * @return	默认群名
     * @author       ChuXY
     */
    public static String getDefaultGroupNameByLocalTime(){
    	StringBuilder name=new StringBuilder();
    	name.append("多人聊天");
    	Time time=new Time();
    	name.append(++time.month+"").append(++time.monthDay+"");
    	return name.toString();
    }

    /**
     * 将屏幕像素写入XML缓存，避免每次都手动获取
     * <br>Created 2014-12-29 下午5:26:54
     * @author       gpy
     */
    public static void writeDisplayMetrics(){
        Context ctx = ApplicationVariable.INSTANCE.applicationContext;
        Point point = new Point();
        ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
        SharedPreferenceHelper.getInstance(ctx).saveIntKey("widthPixels",point.x);
        SharedPreferenceHelper.getInstance(ctx).saveIntKey("heightPixels",point.y);
    }
    /**
     * 从配置读取屏幕宽高   point.x为宽，point.y为高
     * <br>Created 2014-12-29 下午5:26:54
     * @author       gpy
     * @return        point 屏幕宽高
     */
    public static Point readDisplayMetrics(){
        Context ctx = ApplicationVariable.INSTANCE.applicationContext;
        Point point = new Point();
        point.x =  SharedPreferenceHelper.getInstance(ctx).loadIntKey("widthPixels",0);
        point.y = SharedPreferenceHelper.getInstance(ctx).loadIntKey("heightPixels",0);
        return point;
    }
}
